from flask import Blueprint,jsonify,request
import json
from db import db1

bp_goods = Blueprint('goods',__name__)


@bp_goods.route('/goods',methods=['POST','GET'])
def goods():
    if request.method=='POST':
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        res = """insert into goods values(0,"%s",%d)"""%(data['name'],int(data['cid']))
        db1.insert(res)
        return jsonify({'code':200})

    elif request.method=='GET':
        page = int(request.args.get('page'))
        size = int(request.args.get('size'))
        strat = (page-1)*size
        cid = int(request.args.get('cid'))
        if cid >0:
            sql = 'select g.id,g.name,g.cid,c.name as cname from goods as g left join cate as c on g.cid=c.id where g.cid=%d order by id desc limit %d,%d'%(cid,strat,size)
            sql2 = 'select count(id) from goods where cid = %d'%(cid)
        else:
            
            sql = 'select g.id,g.name,g.cid,c.name as cname from goods as g left join cate as c on g.cid=c.id order by id desc limit %d,%d'%(strat,size)
            sql2 = 'select count(id) from goods'
        res = db1.findall(sql)
        total = db1.findone(sql2)
        return jsonify({'code':200,'list':res,'total':total['count(id)']})
    